package org.cyz.tools.common.util;

import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import org.cyz.tools.common.bean.DBInfo;
import org.cyz.tools.common.bean.Settings;
import org.cyz.tools.common.util.sqlite.SQLiteUtil;
import org.cyz.tools.core.assembly.Notify;
import org.cyz.tools.core.assembly.log.Log;

import java.util.Map;
import java.util.Set;

/**
 * @author abccy
 * @title: TreeUiUtil
 * @projectName RedisGUI
 * @description: TODO
 * @date 2020-9-1219:11
 */
public class TreeUtil {

    /**
     * jedis工具
     **/
    private static RedisUtil redisUtil = new RedisUtil();
    /**
     * 图标工具
     */
    private static ImageUtil imageUtil = new ImageUtil();
    /**
     * 每次获取key的数量
     */
    private static int keyCount = getKeyCount();

    private static int startIndex = 0;
    private static int moreStartIndex=0;



    private static int getKeyCount() {
        Settings loadBean= InitDataUtil.getSettings(InitDataUtil.LOAD_KEY);
        if(null!=loadBean){
            return (Integer.valueOf(loadBean.getValue().split("\\.")[0]));
        }
        return 1000;
    }

    public static void reloadKewCount(){
        keyCount=getKeyCount();
    }



    /**
     * 更新key的数量
     *
     * @param treeView
     */
    public static void updateKeyCount(TreeView treeView) {
        TreeItem c = (TreeItem) treeView.getSelectionModel().getSelectedItem();
        String val = c.getParent().getValue().toString();
        if (val.indexOf("(") > 0) {
            String _val = val.substring(val.indexOf("(") + 1, val.indexOf(")"));
            c.getParent().setValue(val.substring(0, val.indexOf("(") + 1) + (Integer.valueOf(_val) - 1) + ")");
        }
    }

    /**
     * 更新treeItem
     *
     * @param treeView
     * @param value
     * @return
     */
    public static void updateKey(TreeView treeView, String value) {
        TreeItem c = (TreeItem) treeView.getSelectionModel().getSelectedItem();
        c.setValue(value);
    }

    /**
     * 删除treeItem
     *
     * @param treeView
     * @return
     */
    public static boolean delTreeItem(TreeView treeView) {
        TreeItem c = (TreeItem) treeView.getSelectionModel().getSelectedItem();
        return c.getParent().getChildren().remove(c);
    }

    /**
     * 删除sqlite中的数据
     *
     * @param value
     * @return
     */
    public static boolean delTreeItemData(String value) {
        return SQLiteUtil.execute("delete from db_info where host='" + value.split(":")[0] + "' and port='" + value.split(":")[1] + "'");
    }


    /**
     * x新增数据入库
     *
     * @param url
     * @return
     */
    public static int addTreeItem(String url) {
        return SQLiteUtil.save(new DBInfo(url));
    }

    /**
     * 关闭连接
     *
     * @param treeView
     * @return
     */
    public static boolean closeTree(TreeView treeView) {
        TreeItem treeItem = (TreeItem) treeView.getSelectionModel().getSelectedItem();
        treeItem.setExpanded(false);
        if (null != treeItem && !treeItem.isExpanded()) {
            Log.info(TreeUtil.class.getSimpleName(),"关闭TreeView...");
            treeItem.getParent().getChildren().removeAll();
            return true;
        }
        return false;
    }

    public static void attrMenuInfo(TreeItem<String> currentSelectItem) {
        //需要进行db的连接
        int dbCount = 0;
        try {
            if (dbCount <= 0) {
                dbCount = RedisUtil.getDBCount();
            }
        } catch (Exception e) {
            Notify.fxToast("数据库个数获取异常!", "异常了", 4);
            return;
        }
        Map<String,String> infos=RedisUtil.getServerInfo();
        for (int i = 0; i < dbCount; i++) {
            //处理每个db下的key
            //List<String> keys = redisUtil.getDBKey(i);
            //遍历db
            TreeItem subItem = new TreeItem<String>("DB" + i + " (" + getDBCount(infos.get("db"+i) ) + ")");
            subItem.setGraphic(ImageUtil.getIcon("db"));
            //加载db下对应的key--分页加载
            Set<String> list = null;
            try {
                if(Integer.valueOf(getDBCount(infos.get("db"+i) ))>0){
                    list = RedisUtil.getDBKeys(i, String.valueOf(startIndex), "*", keyCount);
                }
//                startIndex =startIndex+scanResult.getResult().size();
            } catch (Exception e) {
                e.printStackTrace();
                Notify.fxToast(e.getMessage(), "异常了", 4);
                return;
            }
            if (null != list) {
                list.forEach(result->{
                    String key = result;
                    TreeItem keyItem = new TreeItem<String>();
                    keyItem.setValue(key);
                    if (!"0".equalsIgnoreCase(key)) {
                        keyItem.setGraphic(ImageUtil.getIcon("key"));
                    }
                    subItem.getChildren().add(keyItem);
                });
                if (list.size()>=keyCount) {
                    TreeItem keyItem = new TreeItem<String>();
                    keyItem.setValue("更多...");
                    keyItem.setGraphic(ImageUtil.getIcon("more"));
                    subItem.getChildren().add(keyItem);
                }
            }
            currentSelectItem.getChildren().add(subItem);
        }
    }


    /**
     * 点击更多加载key
     *
     * @param currentSelectItem
     */
    public static void moreKey(TreeItem<String> currentSelectItem, String dbIndex) {
        int loadCount=0;
        //加载db下对应的key--分页加载
        Set<String> list = null;
        try {
            int dI = Integer.parseInt(dbIndex.split(" ")[0].substring(2));
            list = RedisUtil.getDBKeys(dI, String.valueOf(moreStartIndex), "*", keyCount);
            moreStartIndex =moreStartIndex+list.size();
        } catch (Exception e) {
            e.printStackTrace();
            Notify.fxToast(e.getMessage(), "异常了", 4);
            return;
        }
        if (null != list) {
            list.forEach(result->{
                String key = result;
                TreeItem keyItem = new TreeItem<String>();
                keyItem.setValue(key);
                if (!"0".equalsIgnoreCase(key)) {
                    keyItem.setGraphic(ImageUtil.getIcon("key"));
                }
                currentSelectItem.getParent().getChildren().add(keyItem);
            });
            loadCount=list.size();
            if (list.size()>0) {
                TreeItem keyItem = new TreeItem<String>();
                keyItem.setValue("更多...");
                keyItem.setGraphic(ImageUtil.getIcon("more"));
                currentSelectItem.getParent().getChildren().add(keyItem);
            }
        }
        //移除当前加载更多的项目
        currentSelectItem.getParent().getChildren().remove(currentSelectItem);
        Notify.toast(loadCount+" 条Key加载完成!",1000);
    }


    /**
     * 解析db中key的数量
     * @param val
     * @return
     */
    private static String getDBCount(String val) {
        return val==null?"0":val;
    }

}
